// 疫情数据模拟器
export interface EpidemicData {
  name: string
  confirmed: number
  cured: number
  deaths: number
  newConfirmed: number
  newCured: number
  newDeaths: number
  riskLevel: 'low' | 'medium' | 'high'
  vaccinationRate: number
  coord?: [number, number]
}

export interface NationalStats {
  totalConfirmed: number
  totalCured: number
  totalDeaths: number
  newConfirmed: number
  newCured: number
  newDeaths: number
  currentConfirmed: number
  cureRate: number
  deathRate: number
}

export interface TrendData {
  date: string
  confirmed: number
  cured: number
  deaths: number
}

// 全国省份数据
const provinceCoords: Record<string, [number, number]> = {
  '北京': [116.4074, 39.9042],
  '天津': [117.2008, 39.0842],
  '河北': [114.5149, 38.0428],
  '山西': [112.5489, 37.8570],
  '内蒙古': [111.7656, 40.8175],
  '辽宁': [123.4315, 41.8057],
  '吉林': [125.3245, 43.8868],
  '黑龙江': [126.6618, 45.7423],
  '上海': [121.4737, 31.2304],
  '江苏': [118.7969, 32.0603],
  '浙江': [120.1536, 30.2875],
  '安徽': [117.2272, 31.8206],
  '福建': [119.2965, 26.0745],
  '江西': [115.8999, 28.6759],
  '山东': [117.0208, 36.6683],
  '河南': [113.6401, 34.7566],
  '湖北': [114.3055, 30.5931],
  '湖南': [112.9836, 28.1127],
  '广东': [113.2644, 23.1291],
  '广西': [108.3669, 22.8176],
  '海南': [110.3312, 20.0311],
  '重庆': [106.5516, 29.5630],
  '四川': [104.0665, 30.5723],
  '贵州': [106.7070, 26.5982],
  '云南': [102.8332, 24.8801],
  '西藏': [91.1174, 29.6478],
  '陕西': [108.9540, 34.2658],
  '甘肃': [103.8236, 36.0581],
  '青海': [101.7782, 36.6171],
  '宁夏': [106.2586, 38.4717],
  '新疆': [87.6177, 43.7928],
  '台湾': [121.5654, 25.0330],
  '香港': [114.1694, 22.3193],
  '澳门': [113.5491, 22.1987]
}

export class EpidemicDataGenerator {
  private static instance: EpidemicDataGenerator
  private provinceData: Map<string, EpidemicData> = new Map()
  private trendHistory: TrendData[] = []

  static getInstance(): EpidemicDataGenerator {
    if (!this.instance) {
      this.instance = new EpidemicDataGenerator()
    }
    return this.instance
  }

  constructor() {
    this.initializeData()
    this.generateTrendHistory()
  }

  // 生成随机数
  private random(min: number, max: number): number {
    return Math.floor(Math.random() * (max - min + 1)) + min
  }

  // 生成随机小数
  private randomFloat(min: number, max: number, decimals = 2): number {
    return parseFloat((Math.random() * (max - min) + min).toFixed(decimals))
  }

  // 根据人口基数生成合理的疫情数据
  private generateProvinceData(name: string): EpidemicData {
    // 不同省份的人口基数权重
    const populationWeight: Record<string, number> = {
      '广东': 1.0, '山东': 0.8, '河南': 0.75, '四川': 0.7, '江苏': 0.65,
      '河北': 0.6, '湖南': 0.55, '安徽': 0.5, '湖北': 0.48, '浙江': 0.45,
      '广西': 0.4, '云南': 0.38, '江西': 0.35, '辽宁': 0.33, '福建': 0.3,
      '陕西': 0.28, '黑龙江': 0.25, '山西': 0.23, '贵州': 0.2, '重庆': 0.18,
      '吉林': 0.15, '甘肃': 0.13, '内蒙古': 0.12, '新疆': 0.1, '上海': 0.15,
      '北京': 0.12, '天津': 0.08, '海南': 0.06, '宁夏': 0.04, '青海': 0.03,
      '西藏': 0.02, '台湾': 0.15, '香港': 0.05, '澳门': 0.01
    }

    const weight = populationWeight[name] || 0.1
    const baseConfirmed = Math.floor(weight * this.random(1000, 5000))
    const confirmed = baseConfirmed + this.random(0, 500)
    const cured = Math.floor(confirmed * this.randomFloat(0.85, 0.95))
    const deaths = Math.floor(confirmed * this.randomFloat(0.01, 0.03))
    const newConfirmed = this.random(0, Math.floor(confirmed * 0.05))
    const newCured = this.random(0, Math.floor(cured * 0.03))
    const newDeaths = this.random(0, Math.floor(deaths * 0.1))

    // 风险等级评估
    let riskLevel: 'low' | 'medium' | 'high' = 'low'
    const currentConfirmed = confirmed - cured - deaths
    if (currentConfirmed > confirmed * 0.1) riskLevel = 'high'
    else if (currentConfirmed > confirmed * 0.05) riskLevel = 'medium'

    return {
      name,
      confirmed,
      cured,
      deaths,
      newConfirmed,
      newCured,
      newDeaths,
      riskLevel,
      vaccinationRate: this.randomFloat(75, 95),
      coord: provinceCoords[name]
    }
  }

  // 初始化省份数据
  private initializeData(): void {
    Object.keys(provinceCoords).forEach(province => {
      this.provinceData.set(province, this.generateProvinceData(province))
    })
  }

  // 生成趋势历史数据
  private generateTrendHistory(): void {
    const days = 30
    const now = new Date()
    
    for (let i = days - 1; i >= 0; i--) {
      const date = new Date(now.getTime() - i * 24 * 60 * 60 * 1000)
      const dateStr = date.toLocaleDateString('zh-CN')
      
      // 模拟疫情发展趋势
      const dayFactor = (days - i) / days
      const confirmed = Math.floor(50000 + dayFactor * this.random(10000, 30000))
      const cured = Math.floor(confirmed * this.randomFloat(0.85, 0.92))
      const deaths = Math.floor(confirmed * this.randomFloat(0.015, 0.025))

      this.trendHistory.push({
        date: dateStr,
        confirmed,
        cured,
        deaths
      })
    }
  }

  // 获取全国统计数据
  getNationalStats(): NationalStats {
    let totalConfirmed = 0
    let totalCured = 0
    let totalDeaths = 0
    let newConfirmed = 0
    let newCured = 0
    let newDeaths = 0

    this.provinceData.forEach(data => {
      totalConfirmed += data.confirmed
      totalCured += data.cured
      totalDeaths += data.deaths
      newConfirmed += data.newConfirmed
      newCured += data.newCured
      newDeaths += data.newDeaths
    })

    const currentConfirmed = totalConfirmed - totalCured - totalDeaths
    const cureRate = parseFloat((totalCured / totalConfirmed * 100).toFixed(2))
    const deathRate = parseFloat((totalDeaths / totalConfirmed * 100).toFixed(2))

    return {
      totalConfirmed,
      totalCured,
      totalDeaths,
      newConfirmed,
      newCured,
      newDeaths,
      currentConfirmed,
      cureRate,
      deathRate
    }
  }

  // 获取省份数据
  getProvinceData(): EpidemicData[] {
    return Array.from(this.provinceData.values())
  }

  // 获取特定省份数据
  getProvinceById(name: string): EpidemicData | undefined {
    return this.provinceData.get(name)
  }

  // 获取趋势数据
  getTrendData(): TrendData[] {
    return this.trendHistory
  }

  // 获取风险地区排行
  getRiskRanking(): EpidemicData[] {
    return Array.from(this.provinceData.values())
      .sort((a, b) => {
        const aRisk = a.confirmed - a.cured - a.deaths
        const bRisk = b.confirmed - b.cured - b.deaths
        return bRisk - aRisk
      })
      .slice(0, 10)
  }

  // 获取疫苗接种排行
  getVaccinationRanking(): EpidemicData[] {
    return Array.from(this.provinceData.values())
      .sort((a, b) => b.vaccinationRate - a.vaccinationRate)
      .slice(0, 10)
  }

  // 更新数据（模拟实时更新）
  updateData(): void {
    this.provinceData.forEach((data, name) => {
      // 小幅度随机更新
      const newConfirmedChange = this.random(-5, 10)
      const newCuredChange = this.random(0, 15)
      const newDeathsChange = this.random(-1, 2)

      data.newConfirmed = Math.max(0, data.newConfirmed + newConfirmedChange)
      data.newCured = Math.max(0, data.newCured + newCuredChange)
      data.newDeaths = Math.max(0, data.newDeaths + newDeathsChange)

      data.confirmed += Math.max(0, newConfirmedChange)
      data.cured += Math.max(0, newCuredChange)
      data.deaths += Math.max(0, newDeathsChange)

      // 更新疫苗接种率
      data.vaccinationRate = Math.min(100, data.vaccinationRate + this.randomFloat(-0.1, 0.3))

      // 重新评估风险等级
      const currentConfirmed = data.confirmed - data.cured - data.deaths
      if (currentConfirmed > data.confirmed * 0.1) data.riskLevel = 'high'
      else if (currentConfirmed > data.confirmed * 0.05) data.riskLevel = 'medium'
      else data.riskLevel = 'low'
    })

    // 更新趋势数据
    const latestTrend = this.trendHistory[this.trendHistory.length - 1]
    const stats = this.getNationalStats()
    
    // 如果是新的一天，添加新的趋势数据
    const today = new Date().toLocaleDateString('zh-CN')
    if (latestTrend.date !== today) {
      this.trendHistory.push({
        date: today,
        confirmed: stats.totalConfirmed,
        cured: stats.totalCured,
        deaths: stats.totalDeaths
      })

      // 保持最近30天的数据
      if (this.trendHistory.length > 30) {
        this.trendHistory.shift()
      }
    } else {
      // 更新今天的数据
      latestTrend.confirmed = stats.totalConfirmed
      latestTrend.cured = stats.totalCured
      latestTrend.deaths = stats.totalDeaths
    }
  }

  // 创建实时数据流
  createRealTimeStream(callback: (data: any) => void, interval = 5000) {
    const timer = setInterval(() => {
      this.updateData()
      callback({
        timestamp: new Date().toLocaleString('zh-CN'),
        nationalStats: this.getNationalStats(),
        provinceData: this.getProvinceData(),
        trendData: this.getTrendData(),
        riskRanking: this.getRiskRanking(),
        vaccinationRanking: this.getVaccinationRanking()
      })
    }, interval)

    return () => clearInterval(timer)
  }
}

// 导出单例实例
export const epidemicData = EpidemicDataGenerator.getInstance()